/**
 * 
 */
package com.jisheng.xb.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

//import com.jisheng.common.SendSms;
import com.jisheng.xb.common.DateUtil;
import com.jisheng.xb.common.Pager;
import com.jisheng.xb.common.StringUtil;
import com.jisheng.xb.core.exception.BusinessException;
import com.jisheng.xb.entity.Demo;
import com.jisheng.xb.entity.Profile;
import com.jisheng.xb.service.DemoService;
import com.jisheng.xb.web.access.AccessVerifier;

/**
 *
 * @Version: 1.0
 * @Author: LYH
 * 
 *
 */
@Controller
@RequestMapping("/demo")
public class DemoController {
	
	private static Logger log = LogManager.getLogger(DemoController.class);
	
	@Resource(name = "demoService")
	DemoService demoService;
	
	
	/**
	 * 查询列表(rest风格)
	 */
	@RequestMapping(value = {""}, method = { RequestMethod.GET})
	@ResponseBody
    public List<Demo> list(@RequestParam(required = false) String timeStr) {
		Date time = null;
		if(StringUtil.isNullOrEmpty(timeStr)){
			time = DateUtil.toParse(timeStr);
		}
        return demoService.query(time,0,1000);
    }
	
	/**
	 * 查询列表带分页(rest风格)
	 */
	@RequestMapping(value = {"page"}, method = { RequestMethod.GET})
	@ResponseBody
    public Model list4page(Model model,
			@RequestParam(required = false) Integer pageNo,
			@RequestParam(required = false) Integer pageSize) {
		if(pageNo == null) pageNo = 1;
		Pager pager = new Pager();
		pager.setPageNo(pageNo);
		if(pageSize != null){
			pager.setPageSize(pageSize);
		}
		int count = this.demoService.queryCount(null);
		pager.setCount(count);
		List<Demo> demos = this.demoService.query(null,
				pager.getStartIndex(), pager.getPageSize()); 
		model.addAttribute("demos", demos);   
		model.addAttribute("pager", pager);
        return model;
    }
	
	/**
	 * 添加(rest风格)
	 */
	@RequestMapping(value = {""}, method = { RequestMethod.POST})
	@ResponseBody
    public Model create(@RequestParam(required = true) String name,Model model) {
		Integer id = this.demoService.insert(name);
        model.addAttribute("create-id", id);  
        return model;
    }

	/**
	 * 查找(rest风格)
	 */
	@RequestMapping(value = {"/{id}"}, method = { RequestMethod.GET})
	@ResponseBody
    public Demo get(@PathVariable Integer id) {
		log.info("DemoController["+id+"]-"+this);
		Demo demo1 = this.demoService.find(id);
        return demo1;
    }
	
	/**
	 * 删除(rest风格)
	 */
	@RequestMapping(value = {"/{id}"}, method = { RequestMethod.DELETE})
	@ResponseBody
    public Model delete(@PathVariable Integer id,Model model) {
		boolean b = this.demoService.delete(id);
        model.addAttribute("del-id", b+"");  
        return model;
    }
	
	/**
	 * 更新(rest风格)
	 */
	@RequestMapping(value = {"/{id}"}, method = { RequestMethod.PUT})
	@ResponseBody
    public Model update(@PathVariable Integer id,@RequestParam(required = true) String name,Model model) {
		try {
			this.demoService.update(id, name);
			 model.addAttribute("update-id", id+"");  
		} catch (BusinessException e) {
			 model.addAttribute("update-id-error", e.getMessage());
		}
        return model;
    }
	
	/**
	 * 登陆认证
	 */
	@AccessVerifier
	@RequestMapping(value = {"/profile"}, method = { RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
    public Profile testProfile(@RequestParam(required = false)Profile profile,HttpSession session){
		return profile;
    }
	
	/**
	 * 登陆认证，非强制
	 */
	@AccessVerifier(check=false)
	@RequestMapping(value = {"/profile2"}, method = { RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
    public Profile testProfile2(@RequestParam(required = false)Profile profile,
    		HttpServletRequest request){
		return profile;
    }
	
	/**
	 * 异步
	 */
	@RequestMapping(value = {"/async"}, method = { RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
    public Model async(HttpSession session,Model model) {
		this.demoService.it4Async();
		System.out.println("--------testAsync-------");
		return model;
    }
	
	@RequestMapping(value = {"/session"}, method = { RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
    public Model session(HttpSession session,Model model) {
		model.addAttribute("sessionId",session.getId());
		model.addAttribute("sessionValue",session.getAttribute("mysign"));
		if(session.getAttribute("mysign") == null){
			session.setAttribute("mysign", "congfeng");
		}
		return model;
    }
	
	@RequestMapping(value = {"export"}, method = { RequestMethod.GET,RequestMethod.POST})
    public void export(HttpServletResponse response) throws IOException {
		String filename = "test.xls";
    	Workbook wb = new HSSFWorkbook();
        Sheet s = wb.createSheet();
        s.setColumnWidth(0, 4800);
        s.setColumnWidth(1, 4800);
        Row titleRow = s.createRow(0);
        titleRow.createCell(0).setCellValue("编号");
        titleRow.createCell(1).setCellValue("名称");
        Row dataRow1 = s.createRow(1);
        dataRow1.createCell(0).setCellValue("0001");
        dataRow1.createCell(1).setCellValue("名称1");
        Row dataRow2 = s.createRow(2);
        dataRow2.createCell(0).setCellValue("0002");
        dataRow2.createCell(1).setCellValue("名称2");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        wb.write(bos);
        bos.flush();
        byte[] bs = bos.toByteArray();
		OutputStream os = response.getOutputStream();
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename="+filename);
			response.setContentType("application/octet-stream; charset=utf-8");
			os.write(bs);
			os.flush();
		} finally {
			if (os != null) {
				os.close();
			}
		}
    }
	
	/**
	 * 短信
	 */
	/*@RequestMapping(value = {"/sms"}, method = { RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
    public Model sms(Model model,@RequestParam(required = true) String mobile) throws BusinessException {
		boolean b = new SendSms().sendSms(mobile, "动态登陆码：9999");
		if(!b){
			throw new BusinessException("动态登陆码发送失败");
		}
		model.addAttribute("m", "发送成功");
		return model;
    }*/
	
	/**
	 * 微信（dubbo）
	 */
	/*
	@RequestMapping(value = {"/wx"}, method = { RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
    public Model wx(Model model,@RequestParam(required = true) String openId) throws BusinessException {
		WechatUser wuser = weChatService.findWcUserByOpenId(openId);
		model.addAttribute("m", wuser);
		return model;
    }*/
}
